package com.tiantianyuegou.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.R;
import com.tiantianyuegou.constant.Constant;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.SelfUtils;
import com.tiantianyuegou.util.Tools;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 添加收货人地址界面
 * Created by ivany on 2016/1/14.
 */
public class AddAddressActivity extends BaseActivity implements TextWatcher, View.OnClickListener {

    private EditText mEt_name, mEt_phone, mEt_zipCode, mEt_detail;
    private TextView mTxt_area, mTxt_default;
    private ImageView mImg_default;
    private Button mBtn_save;
    private RelativeLayout mRl_area;

    private boolean isDefault = false;
    private LoadingDialog mLoadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_address);
        Tools.changeSystemBar(this);
        setTitle("添加收货地址");
        initViews();
    }

    @Override
    public void findViewByIds() {
        mEt_name = (EditText) findViewById(R.id.add_address_name);
        mEt_phone = (EditText) findViewById(R.id.add_address_phone);
        mEt_detail = (EditText) findViewById(R.id.add_address_detail);
        mEt_zipCode = (EditText) findViewById(R.id.add_address_zipcode);
        mImg_default = (ImageView) findViewById(R.id.add_address_default_img);
        mBtn_save = (Button) findViewById(R.id.add_address_save);
        mTxt_area = (TextView) findViewById(R.id.add_address_area);
        mTxt_default = (TextView) findViewById(R.id.add_address_default_txt);
        mRl_area = (RelativeLayout) findViewById(R.id.add_address_linear_area);
    }

    @Override
    public void initListener() {
        mEt_name.addTextChangedListener(this);
        mEt_phone.addTextChangedListener(this);
        mEt_detail.addTextChangedListener(this);
        mEt_zipCode.addTextChangedListener(this);
        mTxt_area.addTextChangedListener(this);
        mRl_area.setOnClickListener(this);
        mTxt_default.setOnClickListener(this);
        mImg_default.setOnClickListener(this);
        mBtn_save.setOnClickListener(this);
    }

    @Override
    public void initData() {
        mLoadingDialog=new LoadingDialog(this);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

        String name = mEt_name.getText().toString();
        String phone = mEt_phone.getText().toString();
        String zipCode = mEt_zipCode.getText().toString();
        String detail = mEt_detail.getText().toString();
        String area = mTxt_area.getText().toString();
        if (name != null && !"".equals(name) && phone != null && !"".equals(phone) &&zipCode!=null&&!"".equals(zipCode) && area != null && !"".equals(area) && detail != null && !"".equals(detail)) {
            mBtn_save.setEnabled(true);
            mBtn_save.setAlpha(1.0f);
        } else {
            mBtn_save.setEnabled(false);
            mBtn_save.setAlpha(0.5f);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_address_linear_area:
                Intent intent = new Intent(AddAddressActivity.this, SelectProviceActivity.class);
                startActivityForResult(intent, Constant.SELECT_PROVICE_REQUEST);
                break;
            case R.id.add_address_default_img:
            case R.id.add_address_default_txt:
                if (!isDefault) {
                    mImg_default.setImageResource(R.mipmap.select_icon);
                    isDefault = true;
                } else {
                    mImg_default.setImageResource(R.mipmap.unselect_icon);
                    isDefault = false;
                }
                break;
            case R.id.add_address_save:
                String name = mEt_name.getText().toString();
                String phone = mEt_phone.getText().toString();
                String zipCode = mEt_zipCode.getText().toString();
                String detail = mEt_detail.getText().toString();
                if (SelfUtils.isConSpeCharacters(name)) {
                    Toast.makeText(this, "收货人姓名中不能包含特殊字符", Toast.LENGTH_SHORT).show();
                } else if (SelfUtils.containsEmoji(name)) {
                    Toast.makeText(this, "收货人姓名中不能包含emoji表情", Toast.LENGTH_SHORT).show();
                } else if (!SelfUtils.isMobileNO(phone)) {
                    Toast.makeText(this, "手机号码非法，请重新输入", Toast.LENGTH_SHORT).show();
                } else if (!SelfUtils.isZipCode(zipCode)) {
                    Toast.makeText(this, "邮政编码非法，请重新输入", Toast.LENGTH_SHORT).show();
                } else if (SelfUtils.isConSpeCharacters(detail)) {
                    Toast.makeText(this, "详细地址中不能包含特殊字符", Toast.LENGTH_SHORT).show();
                } else if (SelfUtils.containsEmoji(detail)) {
                    Toast.makeText(this, "详细地址中不能包含emoji表情", Toast.LENGTH_SHORT).show();
                } else {
                    mLoadingDialog.setMsg("正在提交收货地址...");
                    mLoadingDialog.show();
                    saveReceiverAddress(name, phone, zipCode, detail);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.SELECT_PROVICE_REQUEST) {
            if (resultCode == Constant.SELECT_PROVICE_RESULT) {
                mTxt_area.setText(Constant.proviceName + " " + Constant.cityName + " " + Constant.zipName);
            }
        }
    }

    //提交到服务器
    private void saveReceiverAddress(String name, String phone, String zipCode, String detail) {
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("tmId", SPHelper.getTmId());
        params.addQueryStringParameter("name", name);
        params.addQueryStringParameter("phone", phone);
        params.addQueryStringParameter("postcode", zipCode);
        params.addQueryStringParameter("proviceId", Constant.proviceID + "");
        params.addQueryStringParameter("cityId", Constant.cityID + "");
        params.addQueryStringParameter("countyId", Constant.zipID + "");
        params.addQueryStringParameter("address", detail);
        if (isDefault) {
            params.addBodyParameter("isdefault", "1");
        } else {
            params.addBodyParameter("isdefault", "0");
        }
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.ADD_ADDRESS, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                mLoadingDialog.dismiss();
                Log.e("TAG", "save address :" + responseInfo.result);
                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("添加地址失败");
                } else {
                    try {
                        JSONObject root = new JSONObject(responseInfo.result);
                        String code = root.getString("code");
                        if ("100".equals(code)) {
                            showMsg("添加地址成功");
                            setResult(Constant.SELECT_ADD_ADDRESS_RESULT);
                            finish();
                        } else {
                            showMsg("添加地址失败");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Log.e("TAG", "failure resquest :" + s);
                showMsg("当前网络不可用，请检查您的网设置");
                mLoadingDialog.dismiss();
            }
        });
    }
}
